package com.cardbaobao.cardbabyclient.ui.activity.web;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.GeolocationPermissions;
import android.webkit.JsPromptResult;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.buried.Google;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.ui.activity.GetPictureActivity;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.ui.activity.web.js.JsInterface;
import com.cardbaobao.cardbabyclient.utils.ArrayUtils;
import com.cardbaobao.cardbabyclient.buried.GoogleAnalyticsUtil;
import com.cardbaobao.cardbabyclient.utils.LogUtils;
import com.cardbaobao.cardbabyclient.widget.WebViewEx;
import com.gyf.barlibrary.ImmersionBar;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/1/10
 * 活动页、以及需要与app本地交互
 */
@SuppressLint("SetJavaScriptEnabled")
public class EventWebViewActivity extends BaseActivity {
    /**
     * 页面加载相关
     */
    public static final String WEB_URL_S = "url";
    public static final String WEB_TITLE_S = "title";
    public static final String WEB_TYPE_I = "type";

    @BindView(R.id.tv_title_title)
    TextView tvTitle;

    @BindView(R.id.iv_title_close)
    ImageView ivClose;

    @BindView(R.id.campaign_rule)
    WebViewEx mWebView;
    @BindView(R.id.web_view_progress)
    ProgressBar mProgress;

    private JsInterface jsInterface;

    private int mType = -1;//0-热门活动 1-首页-大轮播图H5 2-首页-小轮播图H5  3-首页-跑马灯H5 4-极速办卡-轮播图H5 5-极速贷款-轮播图H5
    // 6-办卡进度-轮播图H5  7-首页-热门H5 8-首页-办卡礼H5 9-首页-人气榜H5 10-首页-极速贷H5 11-信用卡-轮播图H5 12-信用卡-跑马灯H5
    // 13-信用卡-热门推荐H5 14-信用卡-人气排行H5 15-信用卡-高端特权H5 16-热门活动-轮播图H5 17-新手办卡-轮播图H5 18-新手办卡详情H5
    // 19-办卡攻略-轮播图H5 20-办卡攻略-热门专题H5 21-办卡攻略-精选攻略H5 22-办卡攻略-羊毛-详情H5 23-办卡攻略-办卡-轮播图H5
    // 24-办卡攻略-提额-轮播图H5 25-办卡攻略-羊毛-轮播图H5 26-办卡攻略-专题-轮播图H5 27-办卡攻略-办卡-详情H5 28-办卡攻略-提额-详情H5
    // 29-办卡攻略-羊毛-详情H5 30-办卡攻略-专题-详情H5 31-贷款-轮播图H5 32-贷款-跑马灯H5 33-贷款按人群分类产品列表-轮播图H5
    // 34-发现-轮播图H5 35-发现-每日红包轮播图H5 36-发现-每日红包-详情H5 37-发现-每日红包-跑马灯H5 38-用户首次启动APP点击广告进入
    // 39-用户在网页中点击链接，唤起app，跳到指定活动页面 40-启动页广告点击进入 41-推送消息H5 43-信用卡提额
    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        ImmersionBar.with(this).keyboardEnable(true).init();
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    mProgress.setVisibility(View.GONE);
                } else {
                    if (mProgress.getVisibility() == View.GONE)
                        mProgress.setVisibility(View.VISIBLE);
                    mProgress.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
                return super.onJsPrompt(view, url, message, defaultValue, result);
            }

            @Override
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                callback.invoke(origin, true, false);
                super.onGeolocationPermissionsShowPrompt(origin, callback);
            }

            //android3.0+
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
                //选择图片
                openFileChooser(uploadMsg, acceptType, null);
            }

            //android4.1+
            public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType, String capture) {
                if("image/*".equals(acceptType)){
                    valueCallback = uploadFile;
                    valueCallbacks = null;
                    takePic("camera".equals(capture));
                }else{
                    uploadFile.onReceiveValue(null);
                }
            }

            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                String[] acceptTypes=fileChooserParams.getAcceptTypes();
                if(acceptTypes.length>0&& ArrayUtils.contains(acceptTypes,"image")){
                    valueCallbacks = filePathCallback;
                    valueCallback = null;
                    takePic(fileChooserParams.isCaptureEnabled());
                }else{
                    filePathCallback.onReceiveValue(null);
                }
                return true;
            }
        });
        mWebView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return super.shouldOverrideUrlLoading(view, request);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                if(mWebView!=null&&mWebView.getVisibility()!=View.VISIBLE){
                    mWebView.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (view.canGoBack()) {
                    ivClose.setVisibility(View.VISIBLE);
                } else {
                    ivClose.setVisibility(View.GONE);
                }
            }

            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                super.onReceivedHttpError(view, request, errorResponse);
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
            }

            @Override
            public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
                super.doUpdateVisitedHistory(view, url, isReload);
                if (jsInterface.isNeedClearHistory()) {
                    jsInterface.clearHistory();
                }
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }
        });
    }

    private void takePic(boolean cantChoosePic) {
        Intent intent = new Intent(EventWebViewActivity.this, GetPictureActivity.class);
        intent.putExtra(GetPictureActivity.CANT_CHOOSE_PIC_B, cantChoosePic);
        startActivityForResult(intent, REQUEST_PIC_CODE);
    }

    /**
     * 消除valueCallback
     */
    private void cancelValueCallback() {
        if (valueCallback != null) {
            valueCallback.onReceiveValue(null);
        }
        if (valueCallbacks != null) {
            valueCallbacks.onReceiveValue(null);
        }
        valueCallbacks = null;
        valueCallbacks = null;
    }

    /**
     * 处理valueCallback
     */
    private void handleValueCallback(String webViewCameraFilePath) {
        if (valueCallbacks != null) {
            valueCallbacks.onReceiveValue(new Uri[]{Uri.fromFile(new File(webViewCameraFilePath))});
        }
        if (valueCallback != null) {
            valueCallback.onReceiveValue(Uri.fromFile(new File(webViewCameraFilePath)));
        }
        valueCallback = null;
        valueCallbacks = null;
    }

    private static final int REQUEST_PIC_CODE = 3000;
    private ValueCallback<Uri> valueCallback;
    private ValueCallback<Uri[]> valueCallbacks;

    @Override
    protected void onResume() {
        super.onResume();
        mWebView.onResume();
        switch (mType) {
            case 0:
                GoogleAnalyticsUtil.setScreenName(Google.HOT_ACTIVITY_DETAIL);
                mCurrentPageId=Self.Page.app_hot_event_detail_page;
                break;
            case 1:
                GoogleAnalyticsUtil.setScreenName(Google.INDEX_BIG_BANNER);
                break;
            case 2:
                GoogleAnalyticsUtil.setScreenName(Google.INDEX_SMALL_BANNER);
                break;
            case 3:
                GoogleAnalyticsUtil.setScreenName(Google.INDEX_MARQUEE);
                break;
            case 4:
                GoogleAnalyticsUtil.setScreenName(Google.SPEED_CREDIT_BANNER);
                break;
            case 5:
                GoogleAnalyticsUtil.setScreenName(Google.SPEED_LOANS_BANNER);
                break;
            case 6:
                GoogleAnalyticsUtil.setScreenName(Google.CREDIT_PROGRESS);
                break;
            case 7:
                GoogleAnalyticsUtil.setScreenName(Google.INDEX_HOT);
                break;
            case 8:
                GoogleAnalyticsUtil.setScreenName(Google.INDEX_CARD_GIFT);
                break;
            case 9:
                GoogleAnalyticsUtil.setScreenName(Google.INDEX_POPULARITY);
                break;
            case 10:
                GoogleAnalyticsUtil.setScreenName(Google.INDEX_SPEED_LOAN);
                break;
            case 11:
                GoogleAnalyticsUtil.setScreenName(Google.CREDIT_CARD_BANNER);
                break;
            case 12:
                GoogleAnalyticsUtil.setScreenName(Google.CREDIT_CARD_MARQUEE);
                break;
            case 13:
                GoogleAnalyticsUtil.setScreenName(Google.CREDIT_CARD_HOT_RECOMMEND);
                break;
            case 14:
                GoogleAnalyticsUtil.setScreenName(Google.CREDIT_CARD_POPULAR);
                break;
            case 15:
                GoogleAnalyticsUtil.setScreenName(Google.CREDIT_CARD_HIGH);
                break;
            case 16:
                GoogleAnalyticsUtil.setScreenName(Google.HOT_ACTIVITY_BANNER);
                break;
            case 17:
                GoogleAnalyticsUtil.setScreenName(Google.NEW_CREDIT_BANNER);
                break;
            case 18:
                GoogleAnalyticsUtil.setScreenName(Google.NEW_CREDIT_DETAIL);
                break;
            case 19:
                GoogleAnalyticsUtil.setScreenName(Google.CREDIT_RAIDERS_BANNER);
                break;
            case 20:
                GoogleAnalyticsUtil.setScreenName(Google.CREDIT_RAIDERS_HOT);
                mCurrentPageId=Self.Page.app_raiders_detail_page;
                break;
            case 21:
                GoogleAnalyticsUtil.setScreenName(Google.CREDIT_RAIDERS_SELECT);
                mCurrentPageId=Self.Page.app_raiders_detail_page;
                break;
            case 22:
                GoogleAnalyticsUtil.setScreenName(Google.CREDIT_RAIDERS_WOOL_DETAL);
                mCurrentPageId=Self.Page.app_raiders_detail_page;
                break;
            case 23:
                GoogleAnalyticsUtil.setScreenName(Google.CREDIT_RAIDERS_CREDIT_BANNER);
                break;
            case 24:
                GoogleAnalyticsUtil.setScreenName(Google.CREDIT_RAIDERS_MENTION_BANNER);
                break;
            case 25:
                GoogleAnalyticsUtil.setScreenName(Google.CREDIT_RAIDERS_WOOL_BANNER);
                break;
            case 26:
                GoogleAnalyticsUtil.setScreenName(Google.CREDIT_RAIDERS_SPECIAL_BANNER);
                break;
            case 27:
                GoogleAnalyticsUtil.setScreenName(Google.CREDIT_RAIDERS_CREDIT_DETAIL);
                mCurrentPageId=Self.Page.app_raiders_detail_page;
                break;
            case 28:
                GoogleAnalyticsUtil.setScreenName(Google.CREDIT_RAIDERS_MENTION_DETAIL);
                mCurrentPageId=Self.Page.app_raiders_detail_page;
                break;
            case 29:
                GoogleAnalyticsUtil.setScreenName(Google.CREDIT_RAIDERS_WOOL_DETAIL);
                mCurrentPageId=Self.Page.app_raiders_detail_page;
                break;
            case 30:
                GoogleAnalyticsUtil.setScreenName(Google.CREDIT_RAIDERS_SPECIAL_DETAIL);
                mCurrentPageId=Self.Page.app_raiders_detail_page;
                break;
            case 31:
                GoogleAnalyticsUtil.setScreenName(Google.LOAN_BANNER);
                break;
            case 32:
                GoogleAnalyticsUtil.setScreenName(Google.LOAN_MARQUEE);
                break;
            case 33:
                GoogleAnalyticsUtil.setScreenName(Google.LOAN_CLASS_PRIDUCT);
                break;
            case 34:
                GoogleAnalyticsUtil.setScreenName(Google.DISCOVER_BANNER);
                break;
            case 35:
                GoogleAnalyticsUtil.setScreenName(Google.DISCOVER_EVERYDAY_RED_BANNER);
                break;
            case 36:
                GoogleAnalyticsUtil.setScreenName(Google.DISCOVER_EVERYDAY_RED_DETAIL);
                mCurrentPageId=Self.Page.app_red_envelopers_detail_page;
                break;
            case 37:
                GoogleAnalyticsUtil.setScreenName(Google.DISCOVER_EVERYDAY_RED_MARQUEE);
                break;
            case 38:
                GoogleAnalyticsUtil.setScreenName(Google.ACTIVITY_FIRST_INTO);
                break;
            case 39:
                GoogleAnalyticsUtil.setScreenName(Google.ACTIVITY_WEB_APP_INTO);
                break;
            case 40:
                GoogleAnalyticsUtil.setScreenName(Google.ACTIVITY_APP_START_PAGE_INTO);
                break;
            case 41:
                GoogleAnalyticsUtil.setScreenName(Google.PUSH_NEWS);
                break;
            case 43:
                mCurrentPageId= Self.Page.app_mention_the_amount_of_particulars;
                break;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        mWebView.onPause();
        if(jsInterface!=null){
            jsInterface.onActivityPause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mWebView.removeAllViews();
        mWebView.destroy();
        mWebView = null;
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        Intent intent = getIntent();
        String url = intent.getStringExtra(WEB_URL_S);
        mType = getIntent().getIntExtra(WEB_TYPE_I, -1);
        String title = intent.getStringExtra(WEB_TITLE_S);
        if (TextUtils.isEmpty(title)) {
            tvTitle.setText("卡宝宝");
        } else {
            tvTitle.setText(title);
        }
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebView.getSettings().setGeolocationEnabled(true);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setUseWideViewPort(true);
        mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.getSettings().setBlockNetworkImage(false);
        mWebView.getSettings().setDefaultTextEncodingName("UTF-8");
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        jsInterface=new JsInterface(this,mWebView);
        mWebView.addJavascriptInterface(jsInterface, "jsInterface");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        if (!TextUtils.isEmpty(url)) {
            mWebView.loadUrl(url);
        }
        LogUtils.d(url);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_event_webview;
    }

    /**
     * 处理返回事件
     */
    private void handleBackEvent() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            finish();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            handleBackEvent();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @OnClick({R.id.iv_title_close, R.id.iv_title_left})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_title_left:
                handleBackEvent();
                break;
            case R.id.iv_title_close:
                finish();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        jsInterface.onActivityResult(requestCode,resultCode,data);
        if(resultCode==RESULT_OK&&data!=null){
            if (requestCode == REQUEST_PIC_CODE) {
                //调用系统拍照后返回
                String webViewCameraFilePath=data.getStringExtra(GetPictureActivity.PIC_PATH);
                if(TextUtils.isEmpty(webViewCameraFilePath)){
                    cancelValueCallback();
                }else{
                    handleValueCallback(webViewCameraFilePath);
                }
            }
        }else{
            if (requestCode == REQUEST_PIC_CODE) {
                cancelValueCallback();
            }
        }
    }
}
